package com.hcbd.tdwt.ui.fuda.common.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;

import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.hcbd.tdwt.ui.fuda.common.activity.ReportPeaceActivity_;
import com.hcbd.tdwt.ui.fuda.common.activity.SosActivity_;
import com.hcbd.tdwt.ui.fuda.setting.activity.PositionReportingActivity_;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.ui.common.dialog.BottomSelectDialog;
import com.hcbd.tdwt.util.BDToGPS;
import com.hcbd.tdwt.util.StringUtil;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.adapter.AmapInfoWinAdapter;
import com.hcbd.tdwt.ui.xingyu.adapter.MapFriendsAdapter;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact_Table;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import static android.content.Context.SENSOR_SERVICE;

@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_location_fuda)
public class LocationFragment extends BaseFragment implements SensorEventListener {
    @ViewById
    ImageView compassPointer;
    @ViewById
    ImageView downloadImg,mapTypeImg,toolboxImg;
    @ViewById
    ImageView locationImg,amplification,narrow;
    @ViewById
    MapView mapView;
    @ViewById
    View showView;
    @ViewById
    RecyclerView mapFriendRV;
    @ViewById
    LinearLayout areaLL,mapBdJumpLL;
    @ViewById
    RelativeLayout compassPointerRL;
    private SensorManager sManager;
    private Sensor mSensorOrientation;
    private int currentDegree;
    //地图对象的操作方法与接口
    private AMap aMap;
    private BottomSelectDialog bottomSelectDialog;
    private MapFriendsAdapter mapFriendsAdapter;
    private boolean isShow=true;

    @AfterViews
    public void init() {
        mapView.onCreate(savedInstanceState);
        List<String>list=new ArrayList<>();
        list.add("卫星图");
        list.add("标准图");
        bottomSelectDialog=new BottomSelectDialog(this.getContext(), "选择图层", list, (index, str) -> {
            if(aMap==null){
                toast("加载中,请稍等");
                return;
            }
            if("卫星图".equals(str)){
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            }else{
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            }
        }, BdToolFactory.FU_DA_BG_TYPE);
        initFriendsAdapter();
/*     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, permissionRequestCode);
        }else{
            initGps();
        }*/
        initGps();
        sManager = (SensorManager) this.getActivity().getSystemService(SENSOR_SERVICE);
        mSensorOrientation = sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
        initMsgRegister();
        if(BdToolFactory.app_type==BdToolFactory.HLCT_BG_TYPE){
            compassPointerRL.setVisibility(View.GONE);
            mapBdJumpLL.setVisibility(View.VISIBLE);
        }
    }
    @Click
    void mapLocImg(){
        Intent intent=new Intent();
        intent.setClass(this.getContext(), PositionReportingActivity_.class);
        startActivity(intent);
    }
    @Click
    void mapSosImg(){
        Intent intent=new Intent();
        intent.setClass(this.getContext(), SosActivity_.class);
        startActivity(intent);
    }
    @Click
    void mapOkImg(){
          Intent intent=new Intent();
          intent.setClass(this.getContext(), ReportPeaceActivity_.class);
          startActivity(intent);
    }

    @Click
    void downloadImg(){
        startActivity(new Intent(this.getContext(), com.amap.api.maps.offlinemap.OfflineMapActivity.class));
    }
    @Click
    void mapTypeImg(){
        BottomSelectDialog.show(bottomSelectDialog);
    }
    @Click
    void locationImg(){
        changeCamera(CameraUpdateFactory.newLatLng(new LatLng(GlobalParams.gpsLatitude, GlobalParams.gpsLongitude)), null, true);
    }
    @Click
    void amplification(){
        changeCamera(CameraUpdateFactory.zoomIn());
    }
    @Click
    void narrow(){
        changeCamera(CameraUpdateFactory.zoomOut());
    }
    @Click
    void toolboxImg(){
        if(areaLL.getVisibility()==View.VISIBLE){
            showView.setVisibility(View.GONE);
            areaLL.setVisibility(View.GONE);
        }else{
            showView.setVisibility(View.VISIBLE);
            areaLL.setVisibility(View.VISIBLE);
        }

    }
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if(sensorEvent.sensor.getType()==Sensor.TYPE_ORIENTATION) {
            roteCompass((int) sensorEvent.values[0]);
        }
    }

    //指针移动
    public void roteCompass(int degree){
        if (degree == 0 || currentDegree == degree||compassPointer==null) {
            return;
        }
        RotateAnimation rotateAnimation = new RotateAnimation(currentDegree, degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  //动画转动角度
        rotateAnimation.setDuration(200); //设置动画持续时间
        rotateAnimation.setFillAfter(true); //设置动画结束后的保留状态
        compassPointer.startAnimation(rotateAnimation);
        currentDegree = degree;
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
    /**
     * 调整缩放级别
     *
     * @param update
     * @param callback
     * @param animated
     */
    private void changeCamera(CameraUpdate update, AMap.CancelableCallback callback, boolean animated) {
        if(aMap==null){
            toast("加载中,请稍等");
            return;
        }
        if (animated) {
            aMap.animateCamera(update, 500, callback);
        } else {
            aMap.moveCamera(update);
        }
    }
    /**
     * 初始化地图
     */
    private void initMap() {
        if (aMap == null&&mapView!=null) {
            aMap = mapView.getMap();
        }
        if(aMap==null){
            return;
        }
        //不显示高德地图默认文字
        aMap.showMapText(true);
        //定义一个UiSettings对象
        UiSettings mUiSettings;
        //实例化UiSettings类对象
        mUiSettings = aMap.getUiSettings();
        //是否显示指南针
        mUiSettings.setCompassEnabled(false);
        //是否显示缩放按钮
        mUiSettings.setZoomControlsEnabled(false);
        //比例尺控件是否显示
        mUiSettings.setScaleControlsEnabled(true);
        //旋转手势关闭
        mUiSettings.setRotateGesturesEnabled(false);
        //是否显示定位到当前位置
        mUiSettings.setMyLocationButtonEnabled(false);
        int zoom;
        if (GlobalParams.gpsLatitude == 0 || GlobalParams.gpsLongitude == 0) {
            //移动中心点到用户当前位置
            zoom=3;
        } else {
            //移动中心点到用户当前位置
            zoom = 16;
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(GlobalParams.gpsLatitude, GlobalParams.gpsLongitude), zoom));
        aMap.setOnMarkerClickListener(markerClickListener);
        initMarker();
        //初始化当前位置
        initAmapLocation();
    }
    // marker 对象被点击时回调的接口
    // 返回 true 则表示接口已响应事件，否则返回false
    AMap.OnMarkerClickListener markerClickListener = marker -> {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }
        return true;
    };
    private List<Marker> markers = new ArrayList<>();
    private List<BoxContact> contactList=new ArrayList<>();
    private void initMarker() {
        markers.clear();
        for (BoxContact boxContact : contactList) {
            String latitude=boxContact.getLatitude();
            String longitude=boxContact.getLongitude();
            if(latitude==null||"0".equals(latitude)||longitude==null||"0".equals(longitude)){
                continue;
            }
            addMarker(boxContact);
        }
        AmapInfoWinAdapter infoWindowView = new AmapInfoWinAdapter(this.getContext());
        infoWindowView.setInfoWindowViewInterface(new AmapInfoWinAdapter.InfoWindowViewInterface() {
            @Override
            public void onSendMsg(String number) {

            }

            @Override
            public void onDetails(AmapInfoWinAdapter.Info info) {

            }
        });
        aMap.setInfoWindowAdapter(infoWindowView);
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(UserMessageVO userMessage){
        initFriendsAdapter();
    }
    private void addMarker(BoxContact boxContact) {
        LatLng wgsLatlng = new LatLng(StringUtil.stringToDouble(boxContact.getLatitude()),StringUtil.stringToDouble(boxContact.getLongitude()));
        LatLng latLng = BDToGPS.castToOtherPoint(wgsLatlng,1);
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(true);
        Marker marker = aMap.addMarker(markerOption);
        marker.setObject(AmapInfoWinAdapter.build(boxContact));
        markers.add(marker);
    }
    public void initFriendsAdapter(){
        if(mapFriendRV==null){
            return;
        }
        contactList= SQLite.select().from(BoxContact.class).where(BoxContact_Table.boxId.notEq(GlobalParams.rdCentreNumber)).queryList();
        if(mapFriendsAdapter==null){
            mapFriendsAdapter=new MapFriendsAdapter(this.getContext(),contactList,1);
            mapFriendsAdapter.setHasStableIds(true);
        }else{
            mapFriendsAdapter.notifyDataSetChanged(contactList);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 1);
        mapFriendRV.setLayoutManager(gridLayoutManager);
        mapFriendRV.setAdapter(mapFriendsAdapter);
        mapFriendsAdapter.setOnItemClickListener(new MapFriendsAdapter.OnItemClickListener() {
            @Override
            public void onPayAttention(BoxContact boxContact) {
                int isPayAttention =boxContact.getIsPayAttention();
                if(isPayAttention==0){
                    boxContact.setIsPayAttention(1);
                }else{
                    boxContact.setIsPayAttention(0);
                }
                boxContact.update();
                initFriendsAdapter();
            }
            @Override
            public void onClick(BoxContact boxContact) {
                String latitude=boxContact.getLatitude();
                String longitude=boxContact.getLongitude();
                if(latitude==null||"0".equals(latitude)||longitude==null||"0".equals(longitude)){
                    toast("当前用户并未发送坐标信息!");
                    return;
                }
                LatLng latLng=BDToGPS.castToOtherLat(new LatLng(StringUtil.stringToDouble(boxContact.getLatitude()), StringUtil.stringToDouble(boxContact.getLongitude())),1);
                changeCamera(CameraUpdateFactory.newLatLng(latLng), null, true);
                for (Marker marker : markers) {
                    AmapInfoWinAdapter.Info obj = (AmapInfoWinAdapter.Info) marker.getObject();
                    if (boxContact.getBoxId().equals(obj.number)) {
                        marker.showInfoWindow();// 显示信息
                        break;
                    }
                }

            }
        });
    }
    @Click
    void showView(){
        if(isShow){
            mapFriendRV.setVisibility(View.GONE);
            isShow=false;
        }else{
            isShow=true;
            mapFriendRV.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 初始化地图定位
     */
    private void initAmapLocation() {
        //初始化定位蓝点样式类
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(getResources().getColor(R.color.colorPrimaryTransparent50));
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.colorPrimaryTransparent50));
        // 设置小蓝点的图标，在xml文件中控制大小
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(getActivity().getLayoutInflater().inflate(R.layout.map_marker_current_location_layout, null)));
        // 连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        //（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.interval(2000);
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
        //设置默认定位按钮是否显示，非必需设置。
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);
        //设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setMyLocationEnabled(true);
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
        if(sManager!=null) {
            sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
        if(sManager!=null){
            sManager.unregisterListener(this);
        }

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }
    /**
     * 调整缩放级别
     *
     * @param update
     */
    public void changeCamera(CameraUpdate update) {
        if(aMap==null){
            return;
        }
        aMap.animateCamera(update, 250, null);
    }
    private void initGps() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        if(locationManager==null){
            toast("获取不到手机定位模块,请重新打开！");
            return;
        }
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showWarnDialog("请打开手机GPS定位，\n否则APP将不能正常使用", view -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constant.TO_OPEN_GPS_REQUEST_CODE);
                hideWarnDialog();
            });
        } else {
            //初始化定位sdk
            MainApp.getInstance().initMap();
            new Handler().postDelayed(() -> initMap(), 4000);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == permissionRequestCode) {
            initGps();
        }
    }
    @OnActivityResult(Constant.TO_OPEN_GPS_REQUEST_CODE)
    void OpenGps(){
        hideWarnDialog();
        initGps();
    }
    @Override
    public void onSwitch(){
        initFriendsAdapter();
    }

    @Override
    public void  onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            //不可见
            sManager.unregisterListener(this);
            EventBus.getDefault().unregister(this);
        }else{
            sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
            initMsgRegister();
        }
    }
}
